"use strict";
Object.defineProperty(exports, "__esModule", {
  value: true
});
const axios_1 = require("axios");
const CryptoJs = require("crypto-js");

const pageSize = 30;

function MD5(data) {
  return CryptoJs.MD5(data)
  .toString(CryptoJs.enc.Hex);
}

function AES(data) {
  let key = CryptoJs.enc.Utf8.parse("e82ckenh8dichen8");
  let text = CryptoJs.enc.Utf8.parse(data);
  return CryptoJs.AES.encrypt(text, key, {
    mode: CryptoJs.mode.ECB,
    padding: CryptoJs.pad.Pkcs7
  }).ciphertext.toString(CryptoJs.enc.Hex);
}

async function EAPI(path, json = {}) {

  let params = [path, JSON.stringify(json)];
  params.push(MD5(
    "nobody" +
    params.join("use") +
    "md5forencrypt"
  ));
  params = AES(params.join("-36cd479b6b5-"));

  return (await (0, axios_1.default)({
    url: path.replace(/^\//, "https://interface.music.163.com/e"),
    method: "POST",
    data: "params=" + params.toUpperCase(),
    headers: {

    },
  })).data;
}

function formatMusicItem(_) {
  _ = _.baseInfo || _.song || _;
  let name = _.name || _.songname;
  let singer = _.ar && _.ar.map(artist => artist.name).join('/') || "";
  let albumName = _.al && _.al.name;

  return {
    id: _.id,
    artist: singer,
    title: name,
    album: albumName,

  }
}

async function searchBase(query, page, type) {
  let data = {
    s: query,
    type: 1,
    limit: pageSize,
    offset: (page - 1) * pageSize,
    total: true,
  };
  let res = await EAPI('/api/cloudsearch/pc', data);
  return res.result;
}

async function search(query, page, type) {
  if (type !== 'lyric') {
    return;
  }

  let searchResult = await searchBase(query, page, 'song');
  let songs = searchResult.songs || [];
  let hasMore = searchResult.hasMore ?? true;
  let songCount = searchResult.songCount ?? 0;

  let isEnd = !hasMore || (page * pageSize >= songCount);

  return {
    isEnd: isEnd,
    data: songs.map(formatMusicItem)
  }
}

async function getLyric(musicItem) {
  let res = await EAPI("/api/song/lyric", {
    id: musicItem.id,
    lv: -1,
    kv: -1,
    tv: -1
  });

  let rawLrc = res?.lrc?.lyric;
  let translation = res?.tlyric?.lyric;

  if (!rawLrc && !translation) {
    return null;
  }

  return {
    rawLrc: rawLrc,
    translation: translation
  };
}


module.exports = {
  platform: "网易云歌词",
  author: 'Ckryin',
  version: "1.0.0",
  srcUrl: "https://gitee.com/rangdl/scripts/raw/master/MusicFree/网易云歌词.js",
  cacheControl: "no-store",
  supportedSearchType: ["lyric"],
  search,
  getLyric
};
